<template>
  <div class="dialog">
    <el-dialog :title="'作业记录' + titleText" :visible.sync="showDialog" width="45%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="鱼塘名称:" prop="fishPondId" class="w50p">
          <el-select filterable clearable v-model="formData.fishPondId" @change="queryBatch">
            <el-option v-for="(item, index) in fishPondList" :key="index" v-show="item.pondName.indexOf('监控') == -1"
              :label="item.pondName" :value="item.fishPondId" />
          </el-select>
        </el-form-item>
        <el-form-item label="批次编号:" prop="productionBatchId" class="w50p">
          <el-select filterable clearable :disabled="!formData.fishPondId" v-model="formData.productionBatchId"
            @change="batchChange">
            <el-option v-for="(item, index) in newBatchList" :key="index" :label="`${item.mnecode}_${item.varietyName}`"
              :value="item.productionBatchId" />
          </el-select>
        </el-form-item>
        <template v-if="auditedIdName !== 'feedingWorkId'">
          <el-form-item label=" 位置：" class="w50p" prop="position">
            <el-input v-model="formData.position" clearable placeholder="请输入位置" />
          </el-form-item>
          <el-form-item label="季节：" class="w50p" prop="season">
            <el-select filterable clearable v-model="formData.season">
              <el-option label="春季" value="春季" />
              <el-option label="夏季" value="夏季" />
              <el-option label="秋季" value="秋季" />
              <el-option label="冬季" value="冬季" />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="作业人:" prop="staffId" class="w50p">
          <el-select clearable  v-model="formData.staffId" :filterable="true" @change="staffChange">
            <el-option v-for="( item, index ) in  staffList " :key="index" :label="item.staffName"
              :value="item.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="auditedIdName !== 'feedingWorkId'" label="作业开始时间：" class="w50p" prop="workBeginTime">
          <el-date-picker v-model="formData.workBeginTime" :picker-options="pickerOptions" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" clearable />
        </el-form-item>
        <el-form-item v-if="auditedIdName == 'feedingWorkId'" label="作业时间：" class="w50p" prop="workDateTime">
          <el-date-picker v-model="formData.workDateTime" :picker-options="pickerOptions" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" clearable />
        </el-form-item>
        <template v-if="auditedIdName !== 'feedingWorkId'">
          <el-form-item label="作业天数：" class="w50p" prop="day">
            <el-input v-model="formData.day" type="number" clearable placeholder="请输入作业天数" />
          </el-form-item>
          <el-form-item label="作业次数：" class="w50p" prop="time">
            <el-input v-model="formData.time" type="number" clearable placeholder="请输入作业次数" />
          </el-form-item>
        </template>
        <template v-if="auditedIdName == 'feedingWorkId' && nowChanceStau == 'add'">
          <div style="width: 100%;  display: flex;" v-for="materialInfo, index in  formData.materialMap " :key="index">
            <el-form-item label="物料名称：" class="w50p" style="width: 50%" :prop="'materialMap.' + index + '.materialId'"
              :rules="{ required: true, message: '请选择物料', trigger: ['change', 'blur'] }">
              <el-select filterable clearable v-model="materialInfo.materialId">
                <el-option v-for="( item, index ) in  materialList " :key="index" :label="item.name"
                  :value="item.materialId" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料数量：" class="w50p" style="width: 40%" :prop="'materialMap.' + index + '.num'"
              :rules="rules.num">
              <el-input v-model="materialInfo.num" min="0" type="number" placeholder="请输入消耗数量">
                <i slot="suffix" class="el-input__icon"> {{ materialObj[formData.materialMap[index].materialId] }}</i>
              </el-input>
            </el-form-item>
            <div style="font-size: 26px;color: #999999;line-height: 36px;  cursor: pointer;">
              <i class="el-icon-remove-outline" style="margin-left: 10px; " @click="removeData(materialInfo, index)"></i>
              <i v-show="formData.materialMap.length == index + 1" class="el-icon-circle-plus-outline"
                style="margin-left: 10px; " @click="plusData(materialInfo, index)"></i>
            </div>
          </div>
        </template>
        <template v-if="auditedIdName == 'feedingWorkId' && nowChanceStau == 'edit'">
          <el-form-item label="物料名称：" class="w50p" prop="materialId">
            <el-select filterable clearable v-model="formData.materialId">
              <el-option v-for="(item, index) in materialList" :key="index" :label="item.name" :value="item.materialId" />
            </el-select>
            <div
              style="width: 100px; height: 36px;background: #ededed;text-align: center;border: 1px solid #dcdcdc;transform: translate(-4px);box-sizing: border-box;">
              {{ materialObj[formData.materialId] }}
            </div>
          </el-form-item>
          <el-form-item label="物料数量：" class="w50p" prop="num">
            <el-input v-model="formData.num" min="0" type="number" clearable placeholder="请填写物料数量0~99999"
              @change="formData.num < 0 ? formData.num = 0 : formData.num > 99999 ? formData.num = 99999 : ''" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import BatchMangeApi from "@/api/batch-mange";
import { dialogMixin } from "@/utils/dialogMixin";
let maxTime = null
export default {
  name: "",
  components: {},
  mixins: [dialogMixin],
  props: {
    auditedIdName: {
      type: String,
      default: "",
    },
    // 弹框名称
    titleText: {
      type: String,
      default: "",
    },
    nowChanceStau: {
      type: String,
      default: "",
    },
    show: {
      type: Boolean,
      default: false,
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      },
    },
    staffList: {
      type: [Array],
      default: () => {
        return [];
      },
    },
    fishPondList: {
      type: [Array],
      default: () => {
        return [];
      },
    },
    batchList: {
      type: [Array],
      default: () => {
        return [];
      },
    },
    materialList: {
      type: [Array],
      default: () => {
        return [];
      },
    },
    eunmApi: {
      type: [Object],
      default: () => {
        return {};
      },
    },
  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && value % 1 === 0 && value > 0) {
          callback();
        } else {
          callback(new Error('请输入大于0的数'));
        }
      } else {
        callback(new Error(rule.emptyMsg));
      }
    };
    let checkNum = (rule, value, callback) => {
      if (value) {
        if (Number(value) > 0 && Number(value) < 99999) {
          callback();
        } else if (Number(value) > 99999) {
          callback(new Error('请输入小于99999的数'));
        } else {
          callback(new Error('请输入大于0的数'));
        }
      } else {
        callback(new Error('请输入物料数量'));
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      materialObj: {},
      rules: {
        fishPondId: [
          {
            required: true,
            message: "请输入鱼塘名称",
            trigger: ["change", "blur"],
          },
        ],
        productionBatchId: [
          {
            required: true,
            message: "请输入批次编号",
            trigger: ["change", "blur"],
          },
        ],
        position: [
          {
            required: true,
            message: "请输入位置",
            trigger: ["change", "blur"],
          },
        ],
        season: [
          {
            required: true,
            message: "请选择季节",
            trigger: ["change", "blur"],
          },
        ],
        staffId: [
          {
            required: true,
            message: "请选择作业人",
            trigger: ["change", "blur"],
          },
        ],
        workBeginTime: [
          {
            required: true,
            message: "请选择作业时间",
            trigger: ["change", "blur"],
          },
        ],
        workDateTime: [
          {
            required: true,
            message: "请选择作业时间",
            trigger: ["change", "blur"],
          },
        ],
        materialId: [
          {
            required: true,
            message: "请选择物料",
            trigger: ["change", "blur"],
          },
        ],
        num: [
          {
            required: true,
            validator: checkNum,
            trigger: ["change", "blur"]
          },
        ],
        day: [
          {
            required: true,
            emptyMsg: "请输入作业天数",
            validator: checkInt,
            trigger: ["change", "blur"],
          },
        ],
        time: [
          {
            required: true,
            emptyMsg: "请输入作业次数",
            validator: checkInt,
            trigger: ["change", "blur"],
          },
        ],
      },
      baseurl: this.$baseurl.fileServiceUrl + "base/files/upload",
      headers: {
        token: sessionStorage.getItem("token"),
        homeBaseId: sessionStorage.getItem("homeBaseId"),
        homeBaseType: sessionStorage.getItem("homeBaseType"),
      },
      images: [],
      fileIdList: [],
      formData: {
        staffId: '',
        materialMap: [{ num: '', materialId: '' }]
      },
      showDialog: this.show,
      newBatchList: this.batchList,
      buildDateTime: ''
    };
  },
  watch: {
    show(v) {
      maxTime = null
      this.$refs["ruleForm"] && this.$refs["ruleForm"].resetFields();
      this.showDialog = v;
      v && this.materialList.forEach(item => {
        if (!item.basicUnitName) {
          item.basicUnitName = ''
        }
        if (!item.auxiliaryUnitName) {
          item.auxiliaryUnitName = ''
        }
        // let auxiliaryUnitNo = `${item.basicUnitName} ${item.basicUnitName && item.auxiliaryUnitName ? '/' : ''}${item.auxiliaryUnitName}`
        let auxiliaryUnitNo = `${item.basicUnitName}`
        this.materialObj[item.materialId] = auxiliaryUnitNo
      })
    },
    nowChanceStau(v) {
      if (v === "add") {
        let staffName = sessionStorage.getItem("staffName")
        let staffId = sessionStorage.getItem("staffId")
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData = {
          staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
          staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
        };
        this.$set(this.formData, 'materialMap', [{}]);

        this.$set(this.formData, 'workBeginTime', this.formatDateTimeMHS(new Date()));
        this.$set(this.formData, 'workDateTime', this.formatDateTimeMHS(new Date()));
        this.formData.materialMap.forEach((item) => {
          this.$set(item, 'num', '')
          this.$set(item, 'materialId', '')
        });
      }
      if (v === "edit") {
        this.formData = JSON.parse(JSON.stringify(this.editObject));
        this.queryBatch(this.formData.fishPondId);
        setTimeout(() => {
          this.batchChange(this.formData.productionBatchId)
        }, 1000);
      }
    },
  },
  created() {
    maxTime = null
  },
  mounted() { },
  methods: {
    plusData(info, index) {
      this.$set(this.formData.materialMap, index + 1, {
        num: '', materialId: ''
      })
    },
    removeData(info, index) {
      if (this.formData.materialMap.length > 1) {
        this.formData.materialMap.splice(index, 1)
      } else {
        this.$message.info('不可以删除哦，至少一条物料记录！')
      }
    },
    batchChange(e) {
      maxTime = ''
      this.formData.workBeginTime = this.formatDateTimeMHS(new Date())
      this.formData.workDateTime = this.formatDateTimeMHS(new Date())
      this.newBatchList.find(item => {
        if (item.productionBatchId === e) {
          this.buildDateTime = item.buildDateTime
          maxTime = new Date(item.buildDateTime)
        }
      })
    },
    changeTime(time) {
      console.log(time)
      let buildDateTime = new Date(this.buildDateTime).getTime(new Date(this.buildDateTime))
      let newtime = new Date(time).getTime(new Date(time))
      if (buildDateTime > newtime) {
        this.formData.workBeginTime = this.buildDateTime
        this.formData.workDateTime = this.buildDateTime
        this.$message.info('作业时间不得小于批次创建时间' + this.buildDateTime + '！')
      }
      console.log(buildDateTime, newtime)
    },
    queryBatch(e) {
      if (e) {
        BatchMangeApi.queryBatchByPondIdUnComplete({ pondId: e }).then((res) => {
          this.newBatchList = res.data;
          this.$set(this.formData, 'productionBatchId', null)
          let filterList = this.newBatchList.filter(item => { return item.productionBatchId == this.editObject.productionBatchId })
          console.log(filterList)
          if (res.data && res.data.length && filterList.length) {
            this.$set(this.formData, 'productionBatchId', filterList[0].productionBatchId)
          } else {
            this.$set(this.formData, 'productionBatchId', null)
          }
        });
      } else {
        this.newBatchList = [];
      }
    },
    staffChange(e) {
      this.staffList.find((item) => {
        if (item.staffId === e) {
          this.formData.staffName = item.staffName;
          return true;
        }
      });
    },
    save(formData) {
      this.formData.overdueFlag = false;
      this.$refs[formData].validate((valid) => {
        if (valid) {
          let maoInfo = {}
          if (this.nowChanceStau == 'add') {
            this.formData.materialMap.forEach(info => {
              maoInfo[info.materialId] = info.num
            })
          }
          this.eunmApi[this.nowChanceStau]({ ...this.formData, ...{ materialMap: maoInfo } }).then((res) => {
            if (res.success === true) {
              this.$message.success("操作成功");
              this.close();
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    },
  },
};
</script>

<style lang="scss" scoped></style>
